const app = getApp();
const call = require('../../../utils/request.js')
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    onPay() {
      console.log('购买')
      let that = this;
      wx.login({
        success: function(res) {
          console.log(res.code)
          //获取openid
          console.log('openId', app.globalData.openId);
          wx.showModal({
            title: '提示',
            content: '确定要购买这个商品么？',
            success(res) {
              if (res.confirm) {
                //生成商户订单
                that._generateOrder(app.globalData.openId)
                // wx.navigateTo({
                //   url: '/pages/msg/msg_success',
                // })
              } else if (res.cancel) {
                // wx.navigateTo({
                //   url: '/pages/msg/msg_fail',
                // })
              }

            }
          })
        }
      })
    },
    _generateOrder(openId) {
      console.log('生成订单');
      var that = this;
      //统一支付
      const url = ``;
      const params = {
        gfee: '1',
        gname: '赞赏费用',
        openId: openId
      };
      call.postData(url, params,
        res => {
          console.log('发起支付');
          var pay = res.data;
          var timeStamp = pay[0].timeStamp;
          var packages = pay[0].package;
          var paySign = pay[0].paySign;
          var nonceStr = pay[0].nonceStr;
          var param = {
            timeStamp: timeStamp,
            packages: packages,
            paySign: paySign,
            signType: "MD5",
            nonceStr: nonceStr
          }
          that._pay(param)
        },
        err => {
          console.log('生成订单失败')
        })
    },
    _pay(param) {
      console.log('支付', param);
      wx.requestPayment({
        timeStamp: param.timeStamp,
        nonceStr: param.nonceStr,
        package: param.packages,
        signType: param.signType,
        paySign: param.paySign,
        success(res) {
          //调用支付成功
          wx.navigateBack({
            delta: 1, //回退上一页
            success() {
              // wx.showToast({
              //   title: '支付成功',
              // })
              wx.navigateTo({
                url: '../msg/msg',
              })
            }
          })
        },
        fail(err) {
          //用户取消支付
          wx.navigateBack({
            delta: 1, //回退上一页
            success() {
              wx.showToast({
                title: err,
                icon: 'none'
              })
            }
          })
        }
      })
    }
  }
})